<template>
  <div class="page">
    <div class="page-top app-container">
      <div>商品套餐销售分析</div>

      <div class="btn-group">
        <div style="margin-right: 300px"
          >城市标签:
          <el-select @change="getList" v-model="queryParams.cityName" placeholder="请选择">
            <el-option v-for="item in cityNameOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </div>
        <el-button plain v-hasPermi="['org:combo:export']" type="primary" @click="handleExport">
          导出数据
        </el-button>

        <el-radio-group v-model="radioValue">
          <el-radio-button label="当天" />
          <el-radio-button label="最近7天" />
          <el-radio-button label="最近30天" />
        </el-radio-group>

        <el-date-picker
          style="width: 260px"
          v-model="state.timeRange"
          type="daterange"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD"
          @calendar-change="dateChange"
          :clearable="false"
        />
      </div>
    </div>
    <div class="app-container" v-loading="state.loading">
      <div class="charts">
        <PieChart class="pie-chart" :data="pieData" name="菜名" :pieCenter="pieCenter" />

        <div class="bar-chart">
          <BaseEchart :echart-options="barOptions" />
        </div>
      </div>

      <el-table :data="tableList">
        <el-table-column label="菜名" align="center" prop="comboName" />
        <el-table-column label="口味" align="center">
          <template #default="{ row }">
            <dict-tag :options="goods_taste" :value="row.taste" />
          </template>
        </el-table-column>
        <el-table-column label="标价（元）" align="center" prop="averageOrderValue" />
        <el-table-column label="投量" align="center" prop="totalVolume" />
        <el-table-column label="销量" align="center" prop="salesVolume" />
        <el-table-column label="销售进度(%)" align="center" prop="salesProgress" />
        <el-table-column label="客单价（元）" align="center" prop="totalSalesAmount" />
      </el-table>

      <pagination
        v-show="state.total > 0"
        :total="state.total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
  </div>
</template>

<script setup name="ComboAnalysis">
import { parseTime } from '@/utils/tools'
import PieChart from '../components/Piechart'
import { onMountedOrActivated } from '@/hooks/common'
import { getComboReport } from '@/api/order/index'
import useGlobalStore from '@/store/modules/global'

const globalStore = useGlobalStore()
const cityNameOptions = computed(() => globalStore.myCityList)
let firstLoad = true
const { proxy } = getCurrentInstance()
const { goods_taste } = proxy.useDict('goods_taste')
const radioValue = ref('最近30天')
const tableList = ref([])
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  cityName: cityNameOptions.value[0]
})
const state = reactive({
  total: 0,
  loading: false,
  timeRange: []
})
const pieCenter = ['30%', '50%']
const pieData = computed(() => {
  const map = new Map()
  tableList.value?.map((item) => {
    const { comboName: name, salesVolume: value = 0 } = item
    if (name) {
      const obj = map.get(name)
      if (obj) {
        obj.value += +value
      } else {
        map.set(name, { name, value })
      }
    }
  })

  return [...map.values()]
})
const barOptions = computed(() => {
  return {
    title: {},
    tooltip: { trigger: 'axis' },
    legend: {
      data: ['销量', '投放'],
      bottom: 0,
      icon: 'circle'
    },
    toolbox: {},
    calculable: true,
    dataset: {
      dimensions: ['comboName', 'salesVolume', 'totalVolume'],
      source: tableList.value
    },
    xAxis: {
      type: 'category',
      axisLabel: {
        //x轴文字的配置
        show: true,
        interval: 0, //使x轴文字显示全
        formatter: function (name) {
          var str = ''
          var length = name.length
          var limitLen = 4 //一行显示几个字
          var rowNumber = Math.ceil(length / limitLen)
          if (length > limitLen) {
            for (var p = 0; p < rowNumber; p++) {
              var tempStr = ''
              var start = p * limitLen
              var end = start + limitLen
              if (p == rowNumber - 1) {
                tempStr = name.substring(start, length)
              } else {
                tempStr = name.substring(start, end) + '\n'
              }
              str += tempStr
            }
          } else {
            str = name
          }
          return str
        }
      }
    },
    yAxis: {},
    series: [
      {
        name: '销量',
        type: 'bar'
      },
      {
        name: '投放',
        type: 'bar'
      }
    ],
    dataZoom: [
      {
        show: tableList.value?.length > 10, // 为true 滚动条出现
        realtime: true,
        type: 'slider', // 有type这个属性，滚动条在最下面，也可以不行，写y：36，这表示距离顶端36px，一般就是在图上面。
        height: 5, // 表示滚动条的高度，也就是粗细
        start: 0, // 表示默认展示0%～80%这一段。
        end: 80,
        backgroundColor: 'transparent',
        bottom: 35,
        textStyle: {
          color: 'transparent'
        }
      },
      {
        type: 'inside',
        xAxisIndex: [0],
        zoomOnMouseWheel: false, //滚轮不触发缩放
        moveOnMouseMove: true, //鼠标移动触发平移
        moveOnMouseWheel: true //鼠标滚轮触发平移
      }
    ]
  }
})

watchEffect(() => handleDateRange(radioValue.value))
watchEffect(() => {
  const [startTime, endTime] = state.timeRange
  queryParams.value.startTime = startTime ? `${startTime} 00:00:00` : ''
  queryParams.value.endTime = endTime ? `${endTime} 23:59:59` : ''

  if (firstLoad) return
  getList()
})

const dateChange = () => (radioValue.value = '')
function handleDateRange(val) {
  const end = parseTime(new Date(), '{y}-{m}-{d}')
  const start = new Date()
  switch (val) {
    case '最近30天':
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      state.timeRange = [parseTime(start, '{y}-{m}-{d}'), end]
      break
    case '最近7天':
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 6)
      state.timeRange = [parseTime(start, '{y}-{m}-{d}'), end]
      break
    case '当天':
      state.timeRange = [parseTime(start, '{y}-{m}-{d}'), end]
      break
    default:
      break
  }
}

async function getList() {
  state.loading = true

  try {
    const r = await getComboReport(queryParams.value)
    tableList.value = r?.rows ?? []
    state.total = r?.total ?? 0
  } finally {
    state.loading = false
  }

  firstLoad = false
}

/** 导出按钮操作 */
function handleExport() {
  const { startTime, endTime } = queryParams.value
  proxy.download(
    'org/orderList/ComboDerive',
    { startTime, endTime },
    `商品套餐销售分析${new Date().getTime()}.xlsx`
  )
}
/**init +  onActivated*/
onMountedOrActivated(getList)
</script>

<style lang="scss" scoped>
.page {
  min-width: 960px;
  overflow-x: scroll;
}
.page-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  align-self: stretch;
  font-size: 16px;
  height: 60px;
  background: var(--el-color-info-light-8);
  .btn-group {
    display: flex;
    align-items: center;
    justify-content: start;
  }
  .el-radio-group {
    margin: 0 10px;
  }
}

.charts {
  display: flex;
  align-items: center;
  justify-content: space-between;
  max-width: 100%;
  .pie-chart {
    flex: 1;
    min-width: 40%;
    height: 400px;
    margin-right: 10px;
  }
  .bar-chart {
    flex: 2;
    height: 500px;
  }
}
</style>
